package com.example.juc;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockTest {

    public static void main(String[] args) {
        int i=(1 << 16) - 1;

        System.out.println(i);
        //reentrantReadWriteLockTest();
        System.out.println("主线程完成");
    }

    public static void reentrantLockTest(){
        ReentrantLock reentrantLock = new ReentrantLock();

        for(int i=0;i<10;i++){
            int finalI = i;
            new Thread(()->{
                reentrantLock.lock();
                sleep(1000L);
                System.out.println("任务"+ finalI +"执行完成");
                reentrantLock.unlock();
            }).start();
        }
    }

    public static void reentrantReadWriteLockTest(){

        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

        for(int i=0;i<10;i++){
            int finalI = i;
            new Thread(()->{
                reentrantReadWriteLock.readLock().lock();
                sleep(1000L);
                System.out.println("任务"+ finalI +"执行完成");
                reentrantReadWriteLock.readLock().unlock();
            }).start();
        }

        for(int i=10;i<20;i++){
            int finalI = i;
            new Thread(()->{
                reentrantReadWriteLock.writeLock().lock();
                sleep(1000L);
                System.out.println("任务"+ finalI +"执行完成");
                reentrantReadWriteLock.writeLock().unlock();
            }).start();
        }

    }


    private static void sleep(Long time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
